package com.franklin.ideaplugin.easytesting.common.resolver.commontype;

import cn.hutool.core.util.ModifierUtil;
import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.common.entity.ChildClass;
import com.franklin.ideaplugin.easytesting.common.entity.MethodParameter;
import com.franklin.ideaplugin.easytesting.common.resolver.IMethodParameterResolver;
import com.franklin.ideaplugin.easytesting.common.utils.JsonUtils;

import java.util.Objects;

/**
 * @author Ye Junhui
 * @since 2023/7/4
 */
public class ChildClassMethodParameterResolver implements IMethodParameterResolver {


    @Override
    public boolean isTarget(MethodParameter methodParameter) {
        return methodParameter.getClassQualifiedName().equals(ChildClass.class.getCanonicalName());
    }

    @Override
    public Class<?> resolveType(MethodParameter methodParameter) {
        if (isTarget(methodParameter)){
            ChildClass childClass = JsonUtils.parseObject(methodParameter.getValue(), ChildClass.class);
            if (Objects.nonNull(childClass)){
                try {
                    return Class.forName(childClass.getSuperClassName());
                } catch (ClassNotFoundException e) {
                    //ignore
                }
            }
        }
        return null;
    }

    @Override
    public Object resolveValue(MethodParameter methodParameter) {
        Class<?> resolveType = resolveType(methodParameter);
        if (Objects.isNull(resolveType) || StrUtil.isBlank(methodParameter.getValue())){
            return null;
        }
        ChildClass childClass = JsonUtils.parseObject(methodParameter.getValue(), ChildClass.class);
        if (Objects.isNull(childClass)){
            return null;
        }
        if (StrUtil.isBlank(childClass.getChildValue())){
            return null;
        }
        try {
            Class<?> childClazz = Class.forName(childClass.getChildClassName());
            return JsonUtils.parseObject(childClass.getChildValue(),childClazz);
        } catch (ClassNotFoundException e) {
            return null;
        }
    }

    @Override
    public Object getDefaultValue(MethodParameter methodParameter) {
        return null;
    }
}
